package com.bjfu.intercepters;

import com.bjfu.utils.JwtUtils;


import com.bjfu.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI()+' '+request.getServletPath().startsWith("/uploads"));
        if(request.getServletPath().startsWith("/uploads")){

            return true;
        }
        // 获取请求头中的 token
        if ("OPTIONS".equals(request.getMethod())) {
            return true; // 预检请求直接返回，不做处理
        }

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            // 没有 token，返回 401 未授权
            response.setStatus(401);
            response.getWriter().write("{\"message\":\"Token is missing\"}");
            return false;
        }
        System.out.println(token);
        // 移除 Bearer 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);  // 去除 "Bearer " 前缀
        }

        try {

            // 获取 role 和 userId
            Long userId = JwtUtils.getUserId(token);
            Integer role=JwtUtils.getRole(token);
            System.out.println("UserId:"+userId+" role:"+role);
            // 获取当前请求的 URI
            String requestURI = request.getRequestURI();

            // 判断角色是否有权限访问该接口
            if ((requestURI.contains("/SuperAdmin") && (role == null || role != 0))
                ||(requestURI.contains("/TeamAdmin") && (role == null || role != 1))
                ||(requestURI.contains("/Member") && (role == null || role != 2))//有问题
                ||(requestURI.contains("/Visitor") && (role == null || role != 3))
            ) {
                // 如果请求的是超级管理员接口，且用户的 role 不是 0（超级管理员），则返回 403 禁止访问
                response.setStatus(403);
                response.getWriter().write("{\"message\":\"Forbidden: You don't have access to this resource\"}");
                return false;
            }

            // 放行请求
            return true;
        } catch (Exception e) {
            // Token 解析失败，返回 401 未授权
            response.setStatus(401);
            response.getWriter().write("{\"message\":\"Invalid token\"}");
            return false;
        }
    }


}